namespace RBAC.Write.Api.Application.Handler.BomHandler
{
    using System;
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.BomCommand;

    /// <summary>
    /// 新增产品 处理器
    /// </summary>
    public class ProductAddHandler : IRequestHandler<ProductAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Product> _productRepo;
        private readonly ILogger<ProductAddHandler> _logger;

        public ProductAddHandler(IBaseRepository<Product> productRepo, ILogger<ProductAddHandler> logger)
        {
            _productRepo = productRepo;
            _logger = logger;
        }

        /// <summary>
        /// 处理新增产品请求
        /// </summary>
        public Task<APIResult<int>> Handle(ProductAddCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                // 自动生成产品编码：CP + yyMMddHHmmss（年两位）
                var code = "CP" + DateTime.Now.ToString("yyMMddHHmmss");
                if (string.IsNullOrWhiteSpace(request.Name))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品名称不能为空", Data = 0 });

                // 唯一性校验（编码）
                var exist = _productRepo.GetFirstOrDefault("Code = @Code AND IsDeleted = 0", new { Code = code });
                if (exist != null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品编码已存在", Data = 0 });

                var entity = new Product
                {
                    Code = code,
                    Name = request.Name!.Trim(),
                    Model = request.Model,
                    Description = request.Description
                };
                if (!string.IsNullOrWhiteSpace(request.CreateUser))
                {
                    entity.CreateUser = request.CreateUser!;
                }

                var newId = _productRepo.Create(entity);

                result.Code = newId > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = newId > 0 ? "新增产品成功" : "新增产品失败";
                result.Data = newId;
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("新增产品被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "新增产品异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "新增产品异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
